package com.haois.mp.database.module.wxserver.rest;

import com.haois.mp.database.commom.enums.ApiResultEnum;
import com.haois.mp.database.module.wxserver.util.MapUtil;
import com.haois.mp.database.module.wxserver.util.TempMsgUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import com.haois.mp.database.commom.CommonConstants;
import com.haois.mp.database.commom.enums.MpTypeEnum;

import com.haois.mp.database.module.common.daomain.TempMessage;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.module.wxserver.service.TempMessageService;
import com.haois.mp.database.util.jx.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by RuiHaoZ on 2018/2/25 16:56
 */
@RestController
@RequestMapping("/api/wxmp/")
public class TempMsgController {

    @Value("${defined.wxmp.base-url}")
    private String baseUrl;
    @Autowired
    private TempMessageService tempMsgService;
    @Autowired
    private IUserTokenService iUserTokenService;

    private int length = 200;
    private Logger logger = LoggerFactory.getLogger(TempMsgController.class);

    /**
     * @api {POST} /api/wxmp/tempMsg/system 模板消息【系统消息】
     * @apiGroup sysTempMsg
     * @apiName sendTempMassage
     * @apiDescription 发送模板消息，如果需要发送给单独个人，输入openiD则发送给个人
     * @apiParam {String} title 标题
     * @apiParam {String} content 内容
     * @apiParam {String} url 点击跳转的url
     * @apiParam {String} openId 加密后的微信号
     * @apiParamExample {json} 请求样例：
     * POST /api/wxmp/tempMsg/system
     * @apiSuccessExample {json} 返回样例:
     * {
     * <p>
     * }
     */
    @PostMapping(value = "/tempMsg/system", params = {"title", "content"})
    public Map sendTempMassage(String title, String content, String url, String openId) throws WxErrorException {
        String timeId = DateUtil.getTimeStamp();
        if (StringUtils.isBlank(url) && content.length() > length) {
            url = baseUrl + CommonConstants.WX_TMSG_SEE + "?id=" + timeId;
        } else if (StringUtils.isNotBlank(url) && content.length() > length) {
            return MapUtil.createMap(ApiResultEnum.API_10.getCode(), "内容过长,请勿超过150字符");
        }
        Map<String, String> mapData = new HashMap<>();
        mapData.put("title", title);
        mapData.put("content", content);
        WxMpTemplate wxMpTemplate = tempMsgService.getTemplateByTitle(TempMsgUtil.title_Sys);
        if (wxMpTemplate == null) {
            return MapUtil.createMap(ApiResultEnum.API_10.getCode(), "模板不存在");
        }
        tempMsgService.saveTempMsg(mapData, timeId, TempMsgUtil.title_Sys);
        TempMessage tempMessage = new TempMessage(mapData);
        tempMessage.setTempId(wxMpTemplate.getTemplateId());
        tempMessage.setTempName(TempMsgUtil.title_Sys);
        tempMessage.setUrl(url);
        tempMessage.setToUser(openId);
        Map result = tempMsgService.sendTo(tempMessage);
        return MapUtil.createMap(ApiResultEnum.API_00.getCode(), "发送模板消息完成", result);
    }

    /**
     * @api {POST} /api/wxmp/tempMsg/member 模板消息【转发消息】
     * @apiGroup sysTempMsg
     * @apiName sendMsgToUser
     * @apiDescription 转发模板消息，你收到一条转发消息【你收到一条转发消息】
     * @apiParam {String} sender 发送人
     * @apiParam {String} remark 类型
     * @apiParam {String} content 内容
     * @apiParamExample {json} 请求样例：
     * POST /api/wxmp/tempMsg/member
     * @apiSuccessExample {json} 返回样例:
     * {
     * <p>
     * }
     */
    @PostMapping(value = "/tempMsg/member", params = {"memberNum", "content"})
    public Map sendMsgToUser(String memberNum, String sender, String content) throws WxErrorException {
        if (content.length() > 100) {
            return MapUtil.createMap(ApiResultEnum.API_00.getCode(), "发送模板消息成功", "内容长度不能超过100字符");
        }
        UserToken userToken = iUserTokenService.findByUserId(memberNum, MpTypeEnum.OFFACCOUNTS.getType());
        String result = "";
        if (userToken != null) {
            Map tempData = new HashMap<String, String>();
            tempData.put("content", content);
            tempData.put("title", "");
            tempData.put("sender", sender);
            tempData.put("receiver", memberNum);
            WxMpTemplate wxMpTemplate = tempMsgService.getTemplateByTitle(TempMsgUtil.title_Fw);
            if (wxMpTemplate != null) {
                TempMessage tempMessage = new TempMessage(tempData);
                tempMessage.setTempId(wxMpTemplate.getTemplateId());
                tempMessage.setTempName(TempMsgUtil.title_Fw);
                tempMessage.setToUser(userToken.getOpenId());
                result = tempMsgService.sendTempMsgToUser(tempMessage, TempMsgUtil.temp_Fw);
            } else {
                result = "模板不存在";
            }
        } else {
            result = "该用户不存在或未绑定微信";
        }
        Map map = MapUtil.createMap(ApiResultEnum.API_00.getCode(), "发送模板消息成功", result);
        return map;
    }

    /**
     * @api {POST} /api/wxmp/tempMsg/members 模板消息【群发消息】
     * @apiGroup sysTempMsg
     * @apiName sendMsgToUserList
     * @apiDescription 转发模板消息，你收到一条群发消息【你收到一条群发消息】
     * @apiParam {String} memberNums 接受人编号，根据 "," 分割
     * @apiParam {String} title 类型
     * @apiParam {String} msgType 消息类型
     * @apiParam {String} content 内容
     * @apiParam {String} sender 发送人
     * @apiParam {String} url 跳转的Url
     * @apiParam {String} id 原模板消息Id
     * @apiParamExample {json} 请求样例：
     * POST /api/wxmp/tempMsg/members
     * @apiSuccessExample {json} 返回样例:
     * {
     * <p>
     * }
     */
    @PostMapping(value = "/tempMsg/members", params = {"memberNums", "sender", "content"})
    public Map sendMsgToUserList(String memberNums, String title, String sender, String msgType, String content, String orgName,
                                 String url, String id) throws WxErrorException {
        String timeId = DateUtil.getTimeStamp();
        if (StringUtils.isBlank(url) && content.length() > length) {
            url = baseUrl + CommonConstants.WX_TMSG_SEE + "?id=" + timeId;
        } else if (StringUtils.isNotBlank(url) && content.length() > length) {
            return MapUtil.createMap(ApiResultEnum.API_10.getCode(), "内容过长,请勿超过150字符");
        }
        Map<String, String> tempData = new HashMap<>(10);
        TempMessage tempMessage = new TempMessage();
        tempData.put("title", title);
        tempData.put("content", content);
        tempData.put("sender", sender);
        tempData.put("orgName", orgName);
        tempData.put("msgType", msgType);
        tempData.put("id", id);
        tempMessage.setUrl(url);
        WxMpTemplate wxMpTemplate = tempMsgService.getTemplateByTitle(TempMsgUtil.title_Mass);
        if (wxMpTemplate == null) {
            return null;
        }
        tempMessage.setTempId(wxMpTemplate.getTemplateId());
        tempMessage.setTempName(TempMsgUtil.title_Mass);
        String[] memberNum = memberNums.split(",");
        tempMessage.setMapData(tempData);
        Map result = tempMsgService.sendTempMsgToUserS(tempMessage, memberNum);
        tempMsgService.saveTempMsg(tempData, timeId, TempMsgUtil.title_Mass);
        return result;
    }

    /**
     * @api {GET} /api/tempMsg/getList 获取模板列表
     * @apiGroup sysTempMsg
     * @apiName getTempMsg
     * @apiDescription 获取模板列表
     * @apiParamExample {json} 请求样例：
     * GET /api/tempMsg/getList
     * @apiSuccessExample {json} 返回样例:
     * {"code":"00","msg":"成功"}
     */
    @GetMapping("/tempMsg/getList")
    public Map getTempMsg() throws WxErrorException {
        List<WxMpTemplate> result = tempMsgService.getTempMsg();
        Map map = MapUtil.createMap(ApiResultEnum.API_00.getCode(), "获取模板列表成功", result);
        return map;
    }

}
